<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row :gutter="40">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model='queryInfo.query' clearable @clear='getUserList'>
            <el-button slot="append" icon="el-icon-search" @click='getUserList'></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>
          <!-- 用户列表 -->
    <el-table :data='userList' border stripe >
            <el-table-column type='index' label='#'></el-table-column>
            <el-table-column label='姓名' prop='username'></el-table-column>
            <el-table-column label='邮箱' prop='email'></el-table-column>
            <el-table-column label='电话' prop='mobile'></el-table-column>
            <el-table-column label='角色' prop='role_name'></el-table-column>
            <el-table-column label='状态' >
                <template slot-scope="scope">
                    <!-- {{scope.row}} -->
                    <!-- scope.row相当于当前行的数据对象 -->
                    <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label='操作' width='180px'>
                <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size='mini' @click="editUser(scope.row.id)"></el-button>
                    <el-button type="danger" icon="el-icon-delete" size='mini' @click="deleteUser(scope.row.id)"></el-button>
                    <el-tooltip effect="dark" content="分配角色" placement="top" :enterable='false'>
                      <el-button type="warning" icon="el-icon-setting"  @click="assignRolesDialog(scope.row)" size='mini'></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
    </el-table>
    <!-- 分页区 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1, 2, 3, 4]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
    </el-card>
      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="40%" @close='closeAddDialog'>
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addDialogUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户对话框 -->
      <el-dialog
        title="编辑用户"
        :visible.sync="editDialogVisible"
        width="40%" @close='closeEditDialog'>
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editDialogUser()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="assignDialogVisible"
        width="40%"
        @close='closeAssignRoles()'>
        <p>当前用户: {{userInfo.username}}</p>
        <p>当前角色: {{userInfo.role_name}}</p>
        <p>
          分配新角色:
        <el-select v-model="selectedRoles" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="assignUserRoles()">确 定</el-button>
        </span>
      </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    var cMobile = (ruler, value, callback) => {
      const regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (regMobile.test(value)) return callback()
      callback(new Error('输入正确手机号'))
    }
    var checkEmail = (ruler, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) return callback()
      callback(new Error('输入合法邮箱'))
    }
    return {
      // 查询参数
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前显示多少条
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 隐藏添加用户对话框
      addDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户验证规则
      addFormRules: {
        username: [
          { required: true, message: '必填用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度为3-10', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '必填密码', trigger: 'blur' },
          { min: 4, max: 10, message: '长度为4-10', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '必填email', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '必填手机号', trigger: 'blur' },
          { validator: cMobile, trigger: 'blur' }
        ]
      },
      // 控制编辑用户对话框显示隐藏
      editDialogVisible: false,
      // 编辑用户查询到的数据
      editForm: {},
      // 编辑用户验证规则
      editFormRules: {
        email: [
          { required: true, message: '必填email', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '必填手机号', trigger: 'blur' },
          { validator: cMobile, trigger: 'blur' }
        ]
      },
      // 分配角色对话框显示隐藏
      assignDialogVisible: false,
      // 需要分配权限的用户信息
      userInfo: {},
      // 角色列表
      rolesList: [],
      // 已经选择的角色id
      selectedRoles: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    addUser () {
      this.addDialogVisible = true
    },
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$messge.error('获取用户数据失败')
      this.userList = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    // 监听pagesize 一页显示个数
    handleSizeChange (newsize) {
    // console.log(newsize)
      this.queryInfo.pagesize = newsize
      this.getUserList()
    },
    // 监听页码值改变
    handleCurrentChange (newpage) {
      this.queryInfo.pagenum = newpage
      this.getUserList()
    },
    // 修改用户状态
    async userStateChange (userInfo) {
      console.log(userInfo)
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$messge.error('请求状态失败')
      }
      this.$message.success('请求成功')
    },
    // 关闭重置对话框
    closeAddDialog () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户逻辑实现
    addDialogUser () {
      this.$refs.addFormRef.validate(async valid => {
        //  如果失败
        if (!valid) return
        // 否则请求数据
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    // 控制对话框显示+根据id请求数据
    async editUser (id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('请求失败')
      this.editForm = res.data
      this.editDialogVisible = true
      console.log(this.editForm)
    },
    // 重置编辑对话框
    closeEditDialog () {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑用户对话框
    editDialogUser () {
      this.$refs.editFormRef.validate(async valid => {
        //  如果失败
        if (!valid) return
        // 否则请求数据
        const { data: res } = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    // 根据id删除用户
    deleteUser (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getUserList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 分配角色对话框显示
    async assignRolesDialog (rowUserInfo) {
      this.userInfo = rowUserInfo
      // console.log(this.userInfo)
      // 展示对话框前，获取角色列表
      const { data: res } = await this.$http.get('roles')
      // 转存角色列表、
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.rolesList = res.data
      console.log(res.data)
      this.assignDialogVisible = true
    },
    // 分配角色实现
    async assignUserRoles () {
      if (!this.selectedRoles) return this.$message.error('未选择角色')
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoles })
      if (res.meta.status !== 200) return this.$message.error('修改失败')
      this.$message.success('修改success')
      this.getUserList()
      this.assignDialogVisible = false
    },
    // 关闭分配角色对话框 重置对话框
    closeAssignRoles () {
      this.selectedRoles = ''
      this.userInfo = {}
    }
  }
}
</script>
<style lang="less" scoped>
</style>
